package lt.mockos.app.client.widget;

import lt.mockos.app.client.cpu.resources.CPUTheme;
import lt.mockos.app.client.cpu.resources.CPUTheme.CPUCss;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

public class MemTable extends Composite {

    private Grid table;
    private static final CPUCss CSS = createCSS();

    public MemTable(int rows, int columns) {
        table = new Grid(rows, columns + 1);
        table.setStyleName(CSS.memTable());
        table.setCellPadding(0);
        table.setCellSpacing(0);
        for (int r = 0; r < rows; r++) {
            table.setWidget(r, 0, new Label(r + "."));
            for (int c = 1; c < columns + 1; c++) {
                TextBox cell = new TextBox();
                cell.setMaxLength(4);
                table.setWidget(r, c, cell);
            }
        }
        table.setCellPadding(0);
        table.setCellSpacing(0);
        initWidget(table);
    }

    public void clear() {
        for (int r = 0; r < table.getRowCount(); r++) {
            for (int c = 1; c < table.getColumnCount(); c++) {
                ((TextBox) table.getWidget(r, c)).setText(null);
            }
        }
    }

    public void setCellValue(int row, int column, String value) {
        getCell(row, column).setText(value);
    }

    public String getCellValue(int row, int column) {
        return getCell(row, column).getText();
    }

    public TextBox getCell(int row, int column) {
        return (TextBox) table.getWidget(row, column + 1);
    }

    private static CPUCss createCSS() {
        CPUTheme theme = GWT.create(CPUTheme.class);
        CPUCss css = theme.css();
        css.ensureInjected();
        return css;
    }
}